<?php

namespace Xrfg\Api\Consume\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Xrfg\Api\Consume\Models\ConsumeAccounts;
use Xrfg\Api\Consume\Requests\AccountRequest;
use Xrfg\Api\Consume\Models\ConsumeAccountLog;
use Xrfg\Api\Consume\Resources\ConsumeAccountLogResource;
use Carbon\Carbon;

class AccountController extends Controller
{
    /**
     * 消费账号信息
     *
     */
    public function account(AccountRequest $request)
    {
        /** @var User $user */
        $user = Auth::user();
        $coin_id = $request->input("coin_id");
        $ConsumeAccount = ConsumeAccounts::firstOrCreate([
                    'user_id' => $user->id,
                    'coin_id' => $coin_id,
                ])->refresh();
        $available = ConsumeAccountLog::where('user_id',$user->id)->where('coin_id',$coin_id)->where('number','<','0')->sum('number');
        return $this->array([
            'name' => $ConsumeAccount->coin->name,
            // 释放收益
            'profit' => -bcadd($available, 0, 4),
            // 冻结收益
            'disabled' => bcadd($ConsumeAccount->disabled, 0, 4),
            // 冻结质押
            'freeze' => bcadd($ConsumeAccount->freeze, 0, 4),
        ]);
    }

    /**
     * 消费账号信息明细.
     * @param Request $request
     */
    public function accountLog(AccountRequest $request)
    {
        // $type = $request->query('type'); // 1-获取，2-解冻，3-兑换，4-支出
        $time = $request->query('time');
        $coin_id = $request->query('coin_id');
        $perPage = $request->query('per_page', 15);
        $perPage = $perPage > 100 ? 100 : $perPage;
        // 时间查询（默认7天内）
        $from_date = Carbon::parse('-7 day')->toDateTimeString();
        $to_date = Carbon::now()->toDateTimeString();
        if($time == 7 ){
            $to_date = $from_date;
            $from_date = Carbon::parse('-1 month')->toDateTimeString();
        }elseif($time == 1){
            $from_date = "2020-01-01";
            $to_date = Carbon::parse('-1 month')->toDateTimeString();
        }
        $accountLogs = ConsumeAccountLog::where('user_id', Auth::id())
            ->where('coin_id', $coin_id)
            ->where('type', '释放冻结收益')
            ->whereBetween('time',array($from_date, $to_date))
            ->orderByDesc('id')
            ->paginate($perPage)
            ->appends($request->only(['type', 'time','per_page']));

        return ConsumeAccountLogResource::collection($accountLogs);
    }
}
